package com.educatioin.manage.web.system.service;

import com.educatioin.manage.common.beans.Response;
import com.educatioin.manage.web.system.po.UserPo;
import com.educatioin.manage.web.system.repository.UserRepository;
import com.educatioin.manage.web.system.request.LoginCheckReq;
import com.educatioin.manage.web.system.response.LoginCheckRsp;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangchen on 2018/4/17.
 */
@Service
public class LoginService {
    @Resource
    private UserRepository userRepository;

    @Transactional
    public LoginCheckRsp authLogin(LoginCheckReq loginCheckReq, HttpServletRequest req){
        HttpSession session = req.getSession();

        LoginCheckRsp loginCheckRsp = new LoginCheckRsp();

        //服务端校验账号密码
        if(StringUtils.isBlank(loginCheckReq.getUserName()) || StringUtils.isBlank(loginCheckReq.getPassword())){
            loginCheckRsp.setReturnCode(Response.RETURN_FAIL_CODE);
            loginCheckRsp.setReturnMsg("用户名或密码不能为空！");
        }

        UserPo userPo = userRepository.findByUsername(loginCheckReq.getUserName());

        //校验用户是否存在
        if(null == userPo){
            loginCheckRsp.setReturnCode(Response.RETURN_FAIL_CODE);
            loginCheckRsp.setReturnMsg("用户不存在！");
            return loginCheckRsp;
        }

        //校验密码是否正确
        if(!userPo.getPassword().equals(loginCheckReq.getPassword())){
            loginCheckRsp.setReturnCode(Response.RETURN_FAIL_CODE);
            loginCheckRsp.setReturnMsg("密码错误！");
            return loginCheckRsp;
        }

        // 密码校验成功 跳转到主页面 并将用户信息存到缓存中
        // session增加存入用户对应的角色ID、角色名称、权限列表（permissions），权限暂时不做考虑
        session.setAttribute("userName", userPo.getUsername());
        session.setAttribute("roleName", userPo.getRole().getRole());
        loginCheckRsp.setReturnCode(Response.RETURN_SUCCESS_CODE);
        loginCheckRsp.setReturnMsg("登录成功！");
        return loginCheckRsp;
    }
}
